package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.config.ConfigFile;
import com.fwtai.config.LocalUserId;
import com.fwtai.poi.ToolExcel;
import com.fwtai.service.AsyncService;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolSms;
import com.fwtai.tool.ToolString;
import com.fwtai.web.AllUserDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 系统用户业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2021-11-10 15:45:05
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class AllUserService{

  @Resource
  private AllUserDao alluserDao;

  @Resource
  private ThreadPoolTaskExecutor taskExecutor;

  @Resource
  private AsyncService asyncService;

  public String listData(PageFormData formData){
    final Integer type = formData.getInteger("type");
    if(type != null && type == 2){
      formData.put("lawyer",type);
    }
    try {
      formData = ToolClient.dataTableMysql(formData);
      if(formData == null)return ToolClient.jsonValidateField();
      final HashMap<String,Object> map = alluserDao.listData(formData);
      return ToolClient.dataTableOK((List<Object>)map.get(ConfigFile.rows),map.get(ConfigFile.total));
    } catch (final Exception e){
      return ToolClient.dataTableException(formData.get("sEcho"));
    }
  }

  public void queryDataExport(final HttpServletRequest request,final HttpServletResponse response){
    final PageFormData formData = ToolClient.getFormData(request);
    final Integer type = formData.getInteger("type");
    if(type != null && type == 2){
      formData.put("lawyer",type);
    }
    formData.remove("accessToken");
    formData.remove("refreshToken");
    final String fileName = new ToolString().getDateTime()+"批量发送用户.xlsx";
    final List<Map<String,Object>> list = alluserDao.queryDataExport(formData);
    final ArrayList<String> fields = new ArrayList<>();
    fields.add("user_name");
    fields.add("name");
    fields.add("number");

    final ArrayList<String> titles = new ArrayList<>();
    titles.add("手机号");
    titles.add("name");
    titles.add("number");

    try {
      if(list.isEmpty()){
        ToolClient.responseJson(ToolClient.createJsonFail(ConfigFile.title + "暂无数据,换个搜索条件试试"),response);
      }else{
        ToolExcel.exportExcel(list,fields,titles,"批量发送短信用户",fileName,response);
      }
    } catch (final Exception e) {
      final String json = ToolClient.createJsonFail(e.getMessage());
      ToolClient.responseJson(json,response);
    }
  }

  public String addSendSms(final HttpServletRequest request){
    final PageFormData formData = new PageFormData(request);
    final String loginId = LocalUserId.get();
    formData.put("loginId",loginId);
    final String kid = String.valueOf(new IdBuilder().getId121L());
    formData.put("kid",kid);
    final String p_code = "code";
    final String p_variate = "variate";
    final String validate = ToolClient.validateField(formData,p_code,p_variate);
    if(validate != null)return validate;
    final String templateCode = formData.getString(p_code);
    final String variate = formData.getString(p_variate);
    final String ids = formData.getString("kids");
    if(ids != null && ids.length() > 0){
      final ArrayList<String> lists = ToolString.keysToList(ids);
      if(lists != null && lists.size() > 0){
        for(int i = lists.size() - 1; i >= 0; i--){
          final String phone = lists.get(i);
          CompletableFuture.runAsync(() -> {
            ToolSms.dispatch(phone,variate,phone,templateCode);
          },taskExecutor);
        }
        formData.put("total",lists.size());
        final ArrayList<HashMap<String,Object>> listParams = new ArrayList<>(lists.size());
        lists.forEach((item)->{
          final HashMap<String,Object> m = new HashMap<>(2);
          m.put("recordId",new IdBuilder().getId121L());
          m.put("phone",item);
          listParams.add(m);
        });
        asyncService.addSmsRecord(formData,listParams);
      }
      return ToolClient.executeRows((lists != null ? lists.size() : 0),"发送成功","发送失败");
    }
    final Integer type = formData.getInteger("type");
    if(type != null && type == 2){
      formData.put("lawyer",type);
    }
    final List<Map<String,Object>> list = alluserDao.queryDataExport(formData);
    if(list != null && list.size() > 0){
      final int size = list.size();
      if(size > 100000){
        return ToolClient.createJsonFail("指定的用户已超过10万,请导出Excel文件去阿里云批量发送");
      }
      final ArrayList<String> lists = new ArrayList<>();
      for(int i = list.size() - 1; i >= 0; i--){
        final String phone = (String) list.get(i).get("user_name");
        lists.add(phone);
        CompletableFuture.runAsync(() -> {
          ToolSms.dispatch(phone,variate,phone,templateCode);
        },taskExecutor);
      }
      formData.put("total",lists.size());
      final ArrayList<HashMap<String,Object>> listParams = new ArrayList<>(lists.size());
      lists.forEach((item)->{
        final HashMap<String,Object> m = new HashMap<>(2);
        m.put("recordId",new IdBuilder().getId121L());
        m.put("phone",item);
        listParams.add(m);
      });
      asyncService.addSmsRecord(formData,listParams);
      return ToolClient.executeRows(list.size(),"成功发送"+list.size()+"个用户","发送全部失败");
    }
    return ToolClient.createJsonFail("没有查询到指定的用户");
  }

  public String getListSearch(final String code){
    if(code == null || code.length() <= 0){
      return ToolClient.queryJson(alluserDao.getListSearch(null));
    }
    return ToolClient.queryJson(alluserDao.getListSearch(code));
  }
}